package com.yuanqi.springboot_banksystem.shiro.realm;

import com.yuanqi.springboot_banksystem.entity.UserEntity;
import com.yuanqi.springboot_banksystem.service.UserService;
import com.yuanqi.springboot_banksystem.utils.MD5Util;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //获取登录用户名
        String username = (String) principalCollection.getPrimaryPrincipal();

        UserEntity userEntity = userService.selectUser(username);

        /**
         *查询用户的角色
         */
        String role = userEntity.getRole();
        Set<String> permissionSet = new HashSet<String>();
        permissionSet.add(role);
        info.setStringPermissions(permissionSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)authenticationToken;

        String username = usernamePasswordToken.getUsername();

        String password = String.valueOf(usernamePasswordToken.getPassword());

        /**
         * 判断是否存在用户
         */
        UserEntity userEntity = userService.selectUser(username);

        if (userEntity == null){
            return null;
        }

        String md5Password = userEntity.getPassword();

        /**
         * 传进来的密码与数据库校验
         */
        if (MD5Util.getMd5Password(password, userEntity.getSalt()).equals(md5Password)){

            return new SimpleAuthenticationInfo(username, password, getName());

        }

        return null;
    }
}
